package com.example.hibernatevalidator.controller;


import com.example.hibernatevalidator.entity.Person;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class PersonController {

    @RequestMapping("/validatePerson")
    @ResponseBody
    public Map<String,Object>  validate(@Valid Person person, BindingResult result){
        System.out.println("进入person");
        Map<String,Object> map = new HashMap<>();
        if(result.hasErrors()){
            List<FieldError>  errors = result.getFieldErrors();
            List<String> stringErrors =  errors.stream().map(e->e.getDefaultMessage()).collect(Collectors.toList());
            map.put("status",0);
            map.put("error",stringErrors);
            return map;
        }
        map.put("status",1);
        map.put("message",person);
        return  map;
    }

}
